<template>
  <view class="mycustom-page">
    <hs-status-bar></hs-status-bar>
    <top-bar :title="'DIY定制'" :haveBack="false"></top-bar>
	<!-- <view class="tabs">
      <u-tabs
        :current="current"
        lineWidth="0"
        lineHeight="0"
        :itemStyle="{ width: '50%' }"
        :inactiveStyle="{ color: '#807D7E', fontSize: '38rpx' }"
        :activeStyle="{
          color: '#3C4242',
          fontSize: '38rpx',
          fontWeight: '700',
        }"
        :list="tabsList"
        @change="switchTabs"
      >
      </u-tabs>
    </view> -->
	<!-- <view class="tabs">
      <u-tabs
        :current="current"
        lineWidth="0"
        lineHeight="0"
        :itemStyle="{ width: '50%' }"
        :inactiveStyle="{ color: '#807D7E', fontSize: '38rpx' }"
        :activeStyle="{
          color: '#3C4242',
          fontSize: '38rpx',
          fontWeight: '700',
        }"
        :list="tabsListCustomized"
        @change="switchTabs"
      >
      </u-tabs>
    </view> -->
	<view class="mymenu hs-row-center hs-align-center">
		<hs-subsection :list="tabsListCustomized" :current="current"
			@switchTab=switchTabs></hs-subsection>
	</view>
    <hs-phoneModel
      v-show="current === 0"
      material-type="myCustom"
      :materialList="materialList"
      ref="phoneModel"
      @handleSelectModel="selectModel"
      @handleSelectMaterial="selectMaterial"
    ></hs-phoneModel>
    
    <!-- DIY编辑区 -->
    <view v-if="current === 0">
      <canvas
        canvas-id="drawCanvas"
        style="
          width: 750rpx;
          height: 750rpx;
          position: absolute;
          left: -750rpx;
          top: -750rpx;
          background: #000;
          z-index: 99;
        "
      ></canvas>

      <view class="decorate-content">
        <!-- <view class="tips" v-if="!canEdit">
					请先挑选机壳
				</view> -->
        <!-- 编辑区 -->
        <view class="eidt-view" @click="editViewClick">
          <diy-edit
            :topMaterialUrl="topMaterialUrl"
            :bottomMaterialUrl="bottomMaterialUrl"
            :list="activeDecorates"
            ref="diyEdit"
            @copyDecorate="copyDecorate"
            @removeDecorate="removeDecorate"
            @writeHistory="writeHistory"
            @changeDecorate="changeDecorate"
          ></diy-edit>
        </view>
        <!-- 素材切换栏 -->
        <view class="type-tabbar">
          <!-- 贴纸 -->
          <view
            class="type-item"
            :class="{ active: decorateType == 0 }"
            @click="selectDecorateType(0)"
          >
            <image
              src="@/static/images/icon/tiezhi.png"
              mode="aspectFit"
            ></image>
            <view class="text"> 贴纸 </view>
          </view>
          <!-- 配饰 -->
          <!-- <view class="type-item" :class="{active:decorateType==1}" @click="selectDecorateType(1)">
						<image src="@/static/images/icon/xiaoxiong.png" mode="aspectFit"></image>
						<view class="text">
							配饰
						</view>
					</view> -->
          <!-- AI人像 -->
          <view
            class="type-item"
            :class="{ active: decorateType == 2 }"
            @click="selectDecorateType(2)"
          >
            <image
              src="@/static/images/icon/aituxiang.png"
              mode="aspectFit"
            ></image>
            <view class="text"> AI图像 </view>
          </view>
          <!-- 模板 -->
          <view
            class="type-item"
            :class="{ active: decorateType == 3 }"
            @click="selectDecorateType(3)"
          >
            <image
              src="@/static/images/icon/moban.png"
              mode="aspectFit"
            ></image>
            <view class="text"> 模板 </view>
          </view>
          <!-- 照片 -->
          <view
            class="type-item"
            :class="{ active: decorateType == 4 }"
            @click="selectDecorateType(4)"
          >
            <image
              src="@/static/images/icon/zhaopian.png"
              mode="aspectFit"
            ></image>
            <view class="text"> 照片 </view>
          </view>
        </view>
        <!-- 操作栏 -->
        <view class="operation-tabbar">
          <view class="left-control">
            <!-- 前进后退 -->
            <image
              src="@/static/images/icon/next.png"
              mode="aspectFit"
              class="control-btn"
              :class="{ disable: historyIndex == 0 }"
              @click="backward"
            >
            </image>
            <image
              src="@/static/images/icon/next.png"
              mode="aspectFit"
              class="control-btn next"
              :class="{ disable: historyIndex == history.length - 1 }"
              @click="forward"
            ></image>
            <!-- 位置微调 -->
            <view v-if="isFocus" class="translate">
              <image
                src="@/static/images/icon/jiantou.png"
                mode="aspectFit"
                class="control-btn left"
                @touchstart="translateDecorate(-2, 0)"
                @touchend="translateDecorateEnd()"
              ></image>
              <image
                src="@/static/images/icon/jiantou.png"
                mode="aspectFit"
                class="control-btn up"
                @touchstart="translateDecorate(0, -2)"
                @touchend="translateDecorateEnd()"
              ></image>
              <image
                src="@/static/images/icon/jiantou.png"
                mode="aspectFit"
                class="control-btn down"
                @touchstart="translateDecorate(0, 2)"
                @touchend="translateDecorateEnd()"
              ></image>
              <image
                src="@/static/images/icon/jiantou.png"
                mode="aspectFit"
                class="control-btn right"
                @touchstart="translateDecorate(2, 0)"
                @touchend="translateDecorateEnd()"
              ></image>
            </view>
          </view>
          <!-- 层级调整 -->
          <view class="coverage" @click="showCoverage">
            <image
              src="@/static/images/icon/cengji.png"
              mode="aspectFit"
            ></image>
          </view>
        </view>
        <!-- 素材列表 -->
        <view
          class="<strong>decorate-list</strong>"
          :class="{ more: moreDecorate, hide: decorateType == null }"
        >
          <view class="more" @click="moreDecorate = !moreDecorate">
            {{ moreDecorate ? "收起 -" : "展开 +" }}
          </view>
          <!-- <text v-if="decorateType==1" class="tips1">注：配饰会以实物的形式贴在手机壳上，无法调整大小</text> -->
          <u-tabs
            v-if="decorateType == 0 || decorateType == 2 || decorateType == 3"
            lineWidth="0"
            lineHeight="30"
            :itemStyle="{ width: '20%', height: '50rpx' }"
            :inactiveStyle="{ color: '#807D7E', fontSize: '26rpx' }"
            :activeStyle="{
              color: '#3C4242',
              fontSize: '26rpx',
              fontWeight: '700',
            }"
            :list="
              decorateType == 0
                ? decorationTagList
                : decorateType == 2
                ? stickerTagList
                : templateTagList
            "
            @change="switchDecorateTab"
            :current="decorateTabsIndex"
          >
          </u-tabs>
          <scroll-view scroll-y="true" class="decorate-scroll">
            <!-- 贴纸 -->
            <view class="list" v-if="decorateType == 0">
              <view
                class="decorate-item"
                v-for="item of decorationList"
                :key="item.id"
                v-show="
                  item.tagIds.includes(decorateTabsId) || decorateTabsId == 0
                "
                @click="selectDecorate(item, 0)"
                :class="{ active: activeDecorates.includes(item) }"
              >
                <radio
                  checked
                  class="radio"
                  v-if="activeDecorates.includes(item)"
                />
                <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
              </view>
            </view>
            <!-- 配饰 -->
            <!-- 					<view class="list" v-if="decorateType==1">
							<view class="decorate-item" v-for="item of accessoriesList" :key="item.id"
								@click="selectDecorate(item,1)" :class="{active:activeDecorates.includes(item)}">
								<radio checked class="radio" v-if="activeDecorates.includes(item)" />
								<image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
							</view>
						</view> -->
            <!-- AI人像 -->
            <view class="list ai-list" v-if="decorateType == 2">
              <view
                class="decorate-item"
                :class="{ active: activeDecorates.includes(item) }"
                :style="item.type == 21 ? 'height: 165rpx;' : ''"
                v-for="item of stickerImageList"
                :key="item.id"
                v-show="item.type == decorateTabsId"
                @click="selectDecorate(item, 2)"
              >
                <radio
                  checked
                  class="radio"
                  v-if="activeDecorates.includes(item)"
                />
                <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
              </view>

              <!--  -->
            </view>
            <!-- <u-button style="width: 200rpx;" v-if="noneAiImage" type="primary" :plain="true" text="去生成ai图像"></u-button> -->
            <view
              class="get-ai-image"
              v-if="noneAiImage && decorateType == 2"
              @click="getAiImage"
            >
              <view class="get-ai-image-text"> 去生成AI图像 </view>
            </view>
            <!-- 模板 -->
            <view class="list" v-if="decorateType == 3">
              <view
                class="decorate-item temp-item"
                v-for="(item) in templateList"
                :key="item.id"
                v-show="item.subType == decorateTabsId"
                @click="getCustomDetailFun(item.id, item.subType)"
                :class="{ active: activeDecorates.includes(item) }"
              >
                <radio
                  checked
                  class="radio"
                  v-if="activeDecorates.includes(item)"
                />
                <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
              </view>

			  <!-- <scroll-view 
				scroll-y 
				:scroll-top="scrollTop"
				@scroll="handleScroll"
				:style="{height: listHeight + 'rpx'}"
				>
				v-show="item.subType == decorateTabsId"

					<view
					class="decorate-item temp-item"
					v-for="(item,index) in visibleData" 
					:key="item.id"
					@click="getCustomDetailFun(item.id, item.subType)"
					:class="{ active: activeDecorates.includes(item) }"
					:style="{transform: `translateY(${startOffset}px)`}"
					>
					<radio
						checked
						class="radio"
						v-if="activeDecorates.includes(item)"
					/>
					<image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
					</view>
				</scroll-view> -->
			  
            </view>
            <!-- 照片 -->
            <view class="list" v-if="decorateType == 4">
              <view class="decorate-item upload" @click="uploadImage">
                <image src="@/static/images/icon/add.png" mode=""></image>
                <view class="text"> 上传照片 </view>
              </view>
              <view
                class="decorate-item"
                v-for="item of customStickerImageList"
                :key="item.id"
                @click="selectDecorate(item, 30)"
                :class="{ active: activeDecorates.includes(item) }"
              >
                <radio
                  checked
                  class="radio"
                  v-if="activeDecorates.includes(item)"
                />
                <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
                
                <view class="delete" @click.stop="deleteImage(item.id)">
                  ×
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
      <view class="btn">
        <view class="btn-next" @click="save" :class="{ disable: !canEdit }">
          确定
        </view>
      </view>
      <view class="">
        <coverage
          ref="coverage"
          @changeIndex="changeIndex"
          @remove="removeDecorate"
          :controlsList="activeDecorates"
          :containerSize="{
            width: '300rpx',
            height: 'calc(100vh - 220rpx)',
            overflow: 'scroll',
          }"
          :controlsSize="{ width: 170, height: 60 }"
        ></coverage>
      </view>
    </view>
    <!-- 我的定制 -->
    <view v-else-if="current === 1">
      <scroll-view
        scroll-y="true"
        class="scroll-box"
        refresher-enabled
        :refresher-triggered="triggered"
        :refresher-threshold="100"
        @refresherrefresh="onRefresh"
        @refresherrestore="onRestore"
        @scrolltolower="scrolltolower"
        :style="{height: `calc(100vh - 280rpx)`}"
      >
        <view class="custom">
          <view
            class="custom-item"
            v-for="(item, index) of customList"
            :key="item.id"
            @click="toView(item)"
          >
            <image
              :src="item.imageUrl"
              lazy-load
              :mode="item.type == 1 ? 'aspectFill' : 'aspectFit'"
              class="img"
              :class="{ img2: item.type == 2 }"
            >
            </image>
            <view
              :class="{
                wait: item.status == 0 || item.status == 1,
                err: item.status == 2,
              }"
              v-if="item.status == 0 || item.status == 1 || item.status == 2"
            >
              <image
                src="@/static/images/icon/wait.png"
                mode="aspectFit"
                v-if="item.status == 0 || item.status == 1"
              ></image>
              <text v-if="item.status == 2">处理失败，请重新上传图片</text>
            </view>
            <view class="resolut" :class="{ resolut2: item.type == 2 }">
              {{ statusOptions[item.status] || "" }}
            </view>
            <!-- v-if="item.status==3" -->
            <view
              class="delete"
              @click.stop="deleteCustom(item.id, index, item.type)"
            >
              ×
            </view>
            <view v-if="!item.read " class="redDot" style="
            height: 13rpx;
            width: 13rpx;
            background-color: red;
            font-size: 13rpx;
            position: absolute;
            top: 17rpx;
            left: 17rpx;
            text-align: center;
            line-height: 13rpx;
            border-radius: 50%;
            opacity: 0.8;">
                  
            </view>
          </view>
        </view>
        <view class="hs-p-b-20" v-if="!isEmpty">
          <u-loadmore :status="status" />
        </view>
        <u-empty
          v-if="isEmpty"
          mode="data"
          text="暂无数据"
          icon="/static/images/icon/data.jpg"
        >
        </u-empty>
      </scroll-view>
      <custom-image-view
        :imageData="imageData"
        ref="customImageView"
        @retry-success="handleRetrySuccess"
      ></custom-image-view>
    </view>
  </view>
</template>

<script>
import {
  getMyCustomList,
  deleteCustom,
  getSkuList,
  getCustomDetail,
  getDecorateList,
  deleteImage,
  customProductRead,
} from "@/api/custom.js";
import {
  generateCanvas,
  submitCustomImage,
  uploadStickerImage,
} from "@/utils/utils.js";
import WebSocket from "@/utils/websocket4.js";
import { mapGetters, mapMutations } from "vuex";
import diyEdit from "@/components/diy/diy-edit.vue";
import eventTracking from "@/utils/eventTracking.js"; //埋点
import {
  connect_throttle,
  connect_debounce
} from "@/utils/throttle.js"; //节流
// import {
//     unReadCount
// 	} from '@/api/custom.js'
import tabbarNoticeMixin from '@/mixins/tabbar-notice'; // 引入tabbarNoticeMixin
export default {
  mixins: [tabbarNoticeMixin], // 使用tabbarNoticeMixin
  components: {
    diyEdit,
  },
  data() {
    return {
      pageReturn:false, //是否为上一页返回的标志位，默认false
      isUploading: false, // 新增：标记是否处于上传状态
      // DIY定制 start

      img: "",
      infoData: {},
      tabsList: [
        {
          name: "图案",
          index: 0,
        },
        {
          name: "机壳",
          index: 1,
        },
        {
          name: "制作",
          index: 2,
        },
      ],
      /* material */
      materialList: [],
    //   activeMaterialId: null,
    //   activeMaterialMap: {},
      /* decorate */
      decorationTagList: [],
      topMaterialUrl: "",
      bottomMaterialUrl: "",
      activeDecorates: [], // 选中的
      moreDecorate: false,
      decorateTabsId: 0, //选中的贴纸标签
      decorateTabsIndex: 0,
      templateTagList: [
        {
          index: 0,
          id: 1,
          name: "整图背景",
          type: 1,
        },
        {
          index: 1,
          id: 3,
          name: "透明背景",
          type: 3,
        },
        {
          index: 2,
          id: 2,
          name: "模板",
          type: 2,
        },
      ], //模板tag标签
      decorationList: [], // 贴纸列表
      templateList: [], // 模板列表
      stickerImageList: [], // AI图片列表
      customStickerImageList: [], // 照片列表
      decorateType: null,
      decorateIndex: 0, // 贴纸排序索引
      isEdit: false,
      isFocus: false, //是否选中贴纸
      // 历史记录
      history: [],
      maxHistory: 20,
      historyIndex: 0,
      // DIY定制 end

      customList: [],
      imageList: [],
      pageSize: 10,
      statusOptions: {
        0: "等待中…",
        1: "生成中…",
        2: "生成失败",
        3: "已完成",
      },
      client: null,
      triggered: false,
      isEmpty: false,
      status: "loading",
      noFresh: false,
      imageShow: false,
      imageData: {},
      tabsListCustomized: [
        {
          name: "DIY定制",
		  index: 0,
        },
        {
          name: "我的定制",
		  index: 1,
          type: "",
        },
        // {
        // 	name: "全部",
        // 	index: 0,
        // 	type: '',
        // },
        // {
        // 	name: "手机壳",
        // 	index: 1,
        // },
        // {
        // 	name: "图片",
        // 	index: 2,
        // },
      ],
      current: this.shouldSelectCustomized() ? 1 : 0, // 默认显示定制页面
      lastMyCustomMaterialMap: {}, // 增加最后一次记录的机型和材质，用于优化切换
      materialList: [],
      infoData: {}, // 详情数据
	  // 新增虚拟列表相关参数
	  itemSize: 214, // 模板项高度(rpx转px需计算)
      buffer: 5,      // 上下缓冲数量
      scrollTop: 0,
      listHeight: 500, // 可见区域高度
      persistKey: 'DIY_EDIT_HISTORY', // 本地存储key
    };
  },
  computed: {
    ...mapGetters(["phoneModelId", "messages", "getMyCustomMaterial"]),
	// visibleData() {
	// 	const start = Math.max(0, this.startIndex - this.buffer)
	// 	const end = Math.min(
	// 	this.startIndex + this.visibleCount + this.buffer,
	// 	this.templateList.length
	// 	)
	// 	// return this.templateList.slice(start, end)
	// 	return this.templateList
	// 	.filter(item => item.subType == this.decorateTabsId) // 先过滤再切片
	// 	.slice(start, end)
	// },
	// startIndex() {
	// 	return Math.floor(this.scrollTop / this.itemSize)
	// },
	// endIndex() {
	// 	return this.startIndex + this.visibleCount
	// },
	// startOffset() {
	// 	return (this.startIndex - this.buffer) * this.itemSize
	// }
  },
  watch: {
    messages(newValue, oldValue) {
      let list = [newValue.customImage, newValue.customPhoneCase];
      list.forEach((item) => {
        let index = this.customList.findIndex((i) => {
          return item.id == i.id;
        });
        if (index != -1) {
          if (item.imageUrl != "") {
            this.customList[index].imageUrl = item.imageUrl;
          }
          this.customList[index].status = item.status;
        }
      });
    },
  },
  methods: {
    ...mapMutations(["setMyCustomMaterial"]),
    //DIY定制 start
    // 新增处理函数，用于处理上传成功后的回调
    handleRetrySuccess() {
      this.getMyCustomListFun(); // 刷新列表
      this.$forceUpdate();       // 强制更新视图
    },
    // 新增状态恢复方法
    restoreEditSession() {
        const session = uni.getStorageSync(this.persistKey);
        if (session) {
            this.activeDecorates = session.activeDecorates;
            this.history = session.history;
            this.historyIndex = session.historyIndex;
            this.decorateIndex = session.decorateIndex;
        }
    },
    // 上传照片
    uploadImage() {
      const _this = this;
      _this.isUploading = true; // 上传开始时标记状态
      uni.chooseMedia({
        count: 1, // 最多可以选择的文件个数
        sourceType: ["album", "camera"], // 从相册选择或是直接调起相机
        mediaType: ["image"], // 可以选定的文件类型
        camera: "back", // 默认后置摄像头，front为前置摄像头
        success: function (res) {
          if (res.tempFiles[0].size > 10 * 1024 * 1024) {
            uni.showToast({
              title: "图片不能大于10M",
              icon: "none",
              duration: 2000,
            });
            return;
          }
          // 新增图片压缩逻辑
          uni.compressImage({
              src: res.tempFiles[0].tempFilePath,
              quality: 80, // 压缩质量80%
              success: compressed => {
                  uploadStickerImage(compressed.tempFilePath, (response) => {
                    let image = JSON.parse(response.data).data;
                    const imageData = {
                      id: image.id,
                      imageUrl: image.imageUrl,
                      height: image.height,
                      width: image.width,
                    };
                    // 将图片放入图片列表中
                    _this.customStickerImageList.unshift(imageData);
                    // 将图片放入贴纸列表中
                    _this.selectDecorate(imageData, 30);
                    _this.isUploading = false; // 上传完成后重置状态
                  });
              },
              fail: (err) => {
                  // 压缩失败仍上传原图
                 console.error("压缩失败", err);
              }
          });
          // // 上传图片
          // uploadStickerImage(res.tempFiles[0].tempFilePath, (response) => {
          //   let image = JSON.parse(response.data).data;
          //   const imageData = {
          //     id: image.id,
          //     imageUrl: image.imageUrl,
          //     height: image.height,
          //     width: image.width,
          //   };
          //   // 将图片放入图片列表中
          //   _this.customStickerImageList.unshift(imageData);
          //   // 将图片放入贴纸列表中
          //   _this.selectDecorate(imageData, 30);
          //   _this.isUploading = false; // 上传完成后重置状态
          // });
        },
        fail: function (err) {
          console.error("选择失败", err);
        },
      });
    },
    // 获取贴纸库
    async getDecorateListFun(str) {
      let [{...item}] = this.materialList.filter((d)=>{return d.id == this.$refs.phoneModel.activeMaterialIndex})
      await getDecorateList({
        materialMap: {
          10: item.materialMap[10],
        //   11: this.infoData.phoneModelId,
			// 11: this.infoData.materialMap[11]
          11: item.materialMap[11],
        },
      }).then((res) => {
        console.log("getDecorateList", res);
        // 贴纸列表0
        this.decorationList = res.data.decorationList;
        // 配饰列表1
        // this.accessoriesList = res.data.accessoriesList
        // ai图像列表2
        this.stickerImageList = res.data.stickerImageList;
        // 模板列表3
        this.templateList = res.data.templateList;

        // 新增：数据加载后初始化模板标签,防止点击模板时标签列表为空
        if (str === "init" && this.templateList.length > 0) {
          this.decorateTabsId = this.templateList[0].subType;
          this.decorateTabsIndex = this.templateTagList.findIndex(item => 
            item.id === this.decorateTabsId
          );
        }

        // 照片列表
        this.customStickerImageList = res.data.customStickerImageList;

        // 贴纸tag列表
        this.decorationTagList = [
          {
            id: 0,
            type: 2,
            name: "全部",
          },
          ...res.data.decorationTagList,
        ];
        uni.hideLoading();
        // 渲染模板
        if (str === "init" && this.templateList.length > 0) {
          this.renderModel(this.infoData);
        }
          
      });
    },
    // 选择贴纸列表类型
     selectDecorateType: connect_throttle(async function(type)  { 
      console.log("selectDecorateType", this.decorateType, type);
      if (this.decorateType == type) {
        this.decorateType = null;
        this.moreDecorate = false;
      } else {
        this.decorateType = type;
        if (type == 0) {
          this.decorateTabsId = this.decorationTagList[0].id;
          this.decorateTabsIndex = 0;
        }
        if (type == 2) {
          this.decorateTabsId = 23;
          this.decorateTabsIndex = 0;
        }
        if (type == 3) {
          console.log("点击模板", this.templateList);
          if (this.templateList.length > 0) {
            this.decorateTabsId = this.templateList[0]?.subType;
            this.decorateTabsIndex = this.templateTagList.findIndex((item) => {
              return item.id == this.decorateTabsId;
            });
            console.log("点击模板2", this.decorateTabsIndex);
          }else{
            // 确保当templateList为空时有默认值
            this.decorateTabsId = this.templateList[0]?.subType || this.templateTagList[0]?.id;
            this.decorateTabsIndex = 0; // 强制指向第一个标签
          }
        }
      }
    },2000),
    // 切换贴纸标签
    switchDecorateTab(e) {
      this.decorateTabsId = e.id;
      this.decorateTabsIndex = e.index;
    },
    // 选择贴纸
    selectDecorate(item, type) {
      console.log("selectDecorate", item, type);
      let newItem = JSON.parse(JSON.stringify(item));
      // 贴纸为用户上传照片时(type==30)，若高度大于1000，则按照1000的0.9倍缩放，若宽度大于750，则按照1000的0.7倍缩放
      let scale =
        item.height > 1000 || item.width > 750
          ? item.height > item.width
            ? 900 / item.height
            : 700 / item.width
          : 1;
          // 获取当前最大索引值
    const maxIndex = this.activeDecorates.length > 0 
    ? Math.max(...this.activeDecorates.map(d => d.index)) 
    : 0; // 新元素的索引为最大索引值加1
      newItem = Object.assign(newItem, {
        type,
        x: 500 - newItem.width / 2, //居中
        y: 500 - newItem.height / 2,
        scaleX: type == "30" ? scale : 1,
        scaleY: type == "30" ? scale : 1,
        // scaleX: 1,
        // scaleY: 1,
        rotationAngle: 0,
        index: maxIndex + 1,
        sortId: this.decorateIndex,
      });
      this.activeDecorates.push(newItem);
      this.activeDecorates.sort((a, b) => {
        return b.index - a.index;
      });
      this.decorateIndex++;
      // this.decorateType = null
      this.writeHistory(this.activeDecorates);
      this.moreDecorate = false;
    },
    // 复制贴纸
    copyDecorate(data) {
      data.sortId = this.decorateIndex;
      this.activeDecorates.push(data);
      this.activeDecorates.sort((a, b) => {
        return b.index - a.index;
      });
      this.decorateIndex++;
      this.writeHistory(this.activeDecorates);
    },
    // 移除贴纸
    removeDecorate(data) {
      let index = this.activeDecorates.findIndex((item) => {
        return item.sortId == data;
      });
      this.activeDecorates.splice(index, 1);
      this.$refs.diyEdit.setFocus();
      this.writeHistory(this.activeDecorates);
    },
    // 微调贴纸位置
    translateDecorate(x, y) {
      this.$refs.diyEdit.translate(x, y);
      this.translateTimer = setInterval(() => {
        this.$refs.diyEdit.translate(x, y);
      }, 100);
    },
    translateDecorateEnd() {
      clearInterval(this.translateTimer);
      // this.writeHistory(this.activeDecorates)
    },
    // 显示图层调整窗口
    showCoverage() {
      this.$refs.diyEdit.setFocus();
      this.$refs.coverage.isShow = true;
    },
    // 调整贴纸的图层顺序
    changeIndex(data) {
      let index = data.length;
      data.forEach((item) => {
        item.index = index;
        index--;
      });
      this.activeDecorates = data;
      this.writeHistory(this.activeDecorates);
    },
    // 确定保存
    // save() {
    //   uni.showLoading();
    //   let decorateList = this.$refs.diyEdit.decorateList;
    //   let canvasData = {
    //     bottomMaterialUrl: this.bottomMaterialUrl,
    //     topMaterialUrl: this.topMaterialUrl,
    //     stickerImageList: decorateList,
    //     id: this.infoData.id,
    //     skuId: this.infoData.skuId,
    //   };
    //   console.log('canvasData',canvasData);
    //   // 生成效果图
    //   generateCanvas(canvasData, decorateList.length * 300 + 1000).then(
    //     (res) => {
		// 	console.log(res);
    //       this.img = res;
    //       // 提交编辑
    //       submitCustomImage(
    //         res,
    //         {
    //           data: JSON.stringify(canvasData),
    //         },
    //         (r) => {
    //           uni.hideLoading();
    //           console.log(JSON.parse(r.data).data);
    //           this.current = 1;	
    //           this.getMyCustomListFun();
    //         //   if (this.isEdit) {
    //         //     uni.navigateBack();
    //         //   } else {
    //         //     uni.redirectTo({
    //         //       url: `/pages/myCustom/customView?id=${
    //         //         JSON.parse(r.data).data
    //         //       }`,
    //         //     });
    //         //   }
    //           uni.hideLoading();
    //           this.resetEditState(); // 新增状态重置

    //         }
    //       );
    //     }
    //   );
    // },

    async save() {
      uni.showLoading({ title: '生成中...' });
      let decorateList = this.$refs.diyEdit.decorateList;
      let canvasData = {
        bottomMaterialUrl: this.bottomMaterialUrl,
        topMaterialUrl: this.topMaterialUrl,
        stickerImageList: decorateList,
        id: this.infoData.id,
        skuId: this.infoData.skuId,
      };
      
      try {
        const decorateList = this.$refs.diyEdit?.decorateList || [];
        // 修改生成canvas的调用方式
        const res = await generateCanvas(canvasData, decorateList.length * 300 + 1000);
        
        if (!res) {
          throw new Error('生成效果图失败');
        }
        
        // 提交保存（同步操作）
        await new Promise((resolve, reject) => {
          this.img = res; // 保存生成的图片
          submitCustomImage(res, {
            data: JSON.stringify(canvasData),
          }, (r) => {
            // 保存成功后清除历史记录
            uni.removeStorageSync(this.persistKey);
            // ...成功处理...
            // this.$nextTick(() => {
            //   this.current = 1;	
            //   uni.hideLoading();
            //   resolve(true);
            // });
            // 增加数据更新保障逻辑
            this.$nextTick(() => {
                this.getMyCustomListFun('',() => {
                    // 等待列表更新完成后再切换标签
                    this.current = 1;
                    uni.hideLoading();
                    // this.getUnReadCount(); // 刷新未读消息
                    this.checkUnReadMessage(); // 刷新未读消息
                    resolve(true);
                });
            });
          
            // this.getMyCustomListFun();

          //   if (this.isEdit) {
          //     uni.navigateBack();
          //   } else {
          //     uni.redirectTo({
          //       url: `/pages/myCustom/customView?id=${
          //         JSON.parse(r.data).data
          //       }`,
          //     });
          //   }
          });
        });

      
        
      } finally {
        uni.hideLoading();
      }
    },

    // 获取详情
    getCustomDetailFun(id = 0, subType) {
      console.log("getCustomDetailFun", id, subType);
      getCustomDetail({
        // phoneModelId: this.infoData.phoneModelId,
        id,
      }).then((res) => {
        this.infoData = res.data;
        // if (temp) {
        // 	this.infoData.id = null
        // }
        // this.infoData.phoneModelId = res.data.materialMap[11]
        this.getSkuListFun();
        // subType(1, "背景"),    // 手机壳
        // subType(3, "透明背景"),
        // subType(2, "模板"),       // 人像
        if (subType == 1 || subType == 3) {
          let idx = this.activeDecorates.findIndex((item) => {
            return item.background == true;
          });
          if (idx != -1) {
            this.activeDecorates.splice(idx, 1);
          }
          let data = res.data.stickerImageList[0];
          data.index = 0;
          data.sortId = this.decorateIndex;
          this.decorateIndex++;
          this.$nextTick(() => {
            this.activeDecorates.push(data);
            this.writeHistory(this.activeDecorates);
          });
        } else {
          this.renderModel(res.data);
        }
        this.moreDecorate = false;
      });
    },
    // 渲染模板内容
    renderModel(data) {
      console.log("renderModel", data);
      console.log("renderModel2", data.hasOwnProperty('stickerImageList'));
      // 添加贴纸
      this.activeDecorates = [];
      if(data.hasOwnProperty('stickerImageList')){
        data.stickerImageList.forEach((item) => {
          let newItem = JSON.parse(JSON.stringify(item));
          // sortId用于区分多个id相同的贴纸
          newItem.sortId = this.decorateIndex;
          this.activeDecorates.push(newItem);
          this.decorateIndex++;
          this.activeDecorates.sort((a, b) => {
            return b.index - a.index;
          });
        });
      }
      
      // this.writeHistory(this.activeDecorates);
      // this.decorateIndex = this.activeDecorates[0].index
      uni.hideLoading();
    },
    // 点击编辑面板
    editViewClick() {
      this.moreDecorate = false;
      this.$refs.phoneModel.materialListShow = false;
    },
    // 删除照片
    deleteImage(id) {
      const _this = this;
      uni.showModal({
        content: "确认要删除",
        success: function (res) {
          if (res.confirm) {
            deleteImage({
              id,
            }).then((res) => {
              const index1 = _this.customStickerImageList.findIndex((item) => {
                return item.id == id;
              });
              if (index1 != -1) {
                _this.customStickerImageList.splice(index1, 1);
              }
              //
              _this.activeDecorates = _this.activeDecorates.filter((item) => {
                return item.id != id;
              });
              _this.writeHistory(_this.activeDecorates);
              // _this.getUnReadCount(); // 刷新未读消息
              _this.checkUnReadMessage(); // 刷新未读消息
            });
          }
        },
      });
    },
    // 监听贴纸的形变
    changeDecorate(data) {
      // this.activeDecorates = data
      this.writeHistory(data);
    },
    // 新增页面切换拦截
    beforeRouteLeave(to, from, next) {
        if (uni.getStorageSync(this.persistKey)?.length > 0) {
            uni.showModal({
                title: '未保存的更改',
                content: '是否保存当前编辑进度？',
                success: (res) => {
                    if (res.confirm) {
                        this.save().then(next);
                    } else {
                        uni.removeStorageSync(this.persistKey);
                        next();
                    }
                }
            });
        } else {
            next();
        }
    },
    // 读写历史记录
    writeHistory(data) {
      let _data = JSON.parse(JSON.stringify(data));
      // 如果index小于数组长度，则清除掉index之后的数据
      this.history.splice(this.historyIndex + 1);
      // 如果数组超出最大长度，清除掉第一项
      if (this.history.length >= this.maxHistory) {
        this.history.shift();
      }
      // 写入最后一项,index修改为数组最后一项
      this.history.push(_data);
      this.historyIndex = this.history.length - 1;
      console.log('读写历史记录',this.history, this.historyIndex);
      // 新增完整状态存储
      uni.setStorageSync(this.persistKey, {
          activeDecorates: this.activeDecorates,
          history: this.history,
          historyIndex: this.historyIndex,
          decorateIndex: this.decorateIndex
      });
    },
    readHistory(index) {
      this.activeDecorates = JSON.parse(
        JSON.stringify(this.history[this.historyIndex])
      );
      this.$refs.diyEdit.decorateList = this.activeDecorates;
      // console.log('readHistory:', this.history, this.historyIndex);
      this.$refs.diyEdit.setFocus();
    },
    // 前进
    forward() {
      this.historyIndex =
        this.historyIndex >= this.history.length - 1
          ? this.history.length - 1
          : this.historyIndex + 1;
      this.readHistory();
    },
    // 后退
    backward() {
      this.historyIndex = this.historyIndex <= 0 ? 0 : this.historyIndex - 1;
      this.readHistory();
    },
    //DIY定制 end

    // 我的定制列表  start
    getMyCustomListFun(lastId = '', callback) {
      getMyCustomList({
        lastId,
        // type: this.current == 1 ? '' : this.current,
        type: "",
        pageSize: this.pageSize,
      }).then((res) => {
        // this.customList = !lastId ? res.data : this.customList.concat(res.data);
        const clonedData = JSON.parse(JSON.stringify(res.data)).map(item => ({
          ...item,
          read: item.read || false // 保留原有read状态，若无则初始化false
        }));
        this.customList = !lastId ? clonedData : [...this.customList, ...clonedData]; // 使用扩展运算符合并数组
        if (this.customList.length == 0) {
          this.isEmpty = true;
          this.status = "nomore";
        } else if (res.data.length < 10) {
          this.status = "nomore";
          this.isEmpty = false;
        } else {
          this.status = "loadmore";
          this.isEmpty = false;
        }
        this.triggered = false;
        // 新增回调执行
        if(callback) callback(); 
      });
    },
    //我的定制列表  end
    getAiImage() {
      console.log("sss");
      uni.switchTab({
        url: "/pages/example",
      });
    },
    // 选择手机型号
    selectModel(data) {
    //   if (this.phoneModelId === data) {
    //     // 增加机型比对
    //     console.log("机型未变化");
    //     return;
    //   }

	  this.infoData.phoneModelId = data;
    //   this.infoData.materialMap[11] = data;
      this.getSkuListFun(data);
      uni.$u.debounce(() => {
        this.onRefresh();
      });
    },
    async getSkuListFun(phoneModelId) {
      
      console.log("getSkuListFun1", phoneModelId);
		console.log("getSkuListFun2", this.phoneModelId);
    const modelId = phoneModelId ?? this.phoneModelId;
    console.log("modelId", modelId);
      const { data } = await getSkuList({
        // materialMap: { 11: this.infoData.materialMap[11] },
        materialMap: { 11 : modelId },
        pageSize: 50,
      });

      this.materialList = data;
    //   const storedMaterial = this.getCurrentMaterial;

      // 智能匹配策略
      // const idx = data.findIndex(item =>
      // 	storedMaterial?.materialMap[10] === item.materialMap[10]
      // )

      // const finalIndex = idx !== -1 ?
      // 	idx :
      // 	data.findIndex(item => item.defaulted)

      let finalIndex = 0;
      if (data.length > 0) {
        // 使用可选链和空值合并操作符
        // const historyMaterialId =  this.infoData.materialMap[10]; // 先查找历史记录
		const storedMaterial = this.getMyCustomMaterial;
		const historyMaterialId = storedMaterial?.materialMap?.[10];
        // 分步查找策略
        finalIndex = data.findIndex(
          (i) => i.materialMap?.[10] === historyMaterialId
        );

         // 未找到历史材质时查找默认项为镜面黑边
         if (finalIndex === -1) {
          finalIndex = data.findIndex(item => 
            item.name === '镜面黑边'
          );
        }

        // // 未找到历史材质时查找默认项
        // if (finalIndex === -1) {
        //   finalIndex = data.findIndex((item) => item.defaulted);
        // }

        // 双重保险：当默认项也不存在时取首项
        finalIndex = finalIndex >= 0 ? finalIndex : 0;

        finalIndex = Math.max(finalIndex, 0); // 确保下标不小于0
      }
		
		this.infoData.skuId = data[finalIndex].id; // 设置当前材质的skuId
      	this.selectMaterial(data[finalIndex], finalIndex);
    },
    // 选择材质
    // selectMaterial(data, index) {
    //   console.log("selectMaterial", data, index); // 修改为打印整个data对象
	  // // this.infoData.materialMap[10] = data.materialMap[10];
    //   this.setCurrentMaterial(data);
    //   console.log("0001", data);
    //   // console.log('0002',this);
    //   //
    //   this.$refs.phoneModel.activeMaterialIndex = index;
    // //   this.activeMaterialId = data?.materialMap[10];

    //   this.$refs.phoneModel.materialListShow = false;
    // //   this.activeMaterialMap = data.materialMap;
    //   this.topMaterialUrl = data.frameImageUrl;
    //   this.bottomMaterialUrl = data.baseImageUrl;
    //   this.getDecorateListFun(); // 获取装饰品列表
    //   // uni.$u.debounce(() => {
    //   // 	this.onRefresh()
    //   // })
    // },
    selectMaterial(data, index) {
			this.setMyCustomMaterial(data)
			
			// this.activeMaterial = data?.materialMap[10]
			// this.$refs.phoneModel.activeMaterialIndex = index
			this.$refs.phoneModel.activeMaterialIndex = data.id
			console.log('000list',this.materialList);
			// console.log('0001',this.materialList[data.id]);
			if (this.materialList.length > 0) {
				// this.activeMaterialName = this.materialList[index]?.name
				let [{...item}] = this.materialList.filter((d)=>d.name == data.name)
				console.log('item',item);
				this.activeMaterialName = item.name
				console.log('filter',this.activeMaterialName);
        this.$refs.phoneModel.name = item.name
				this.$refs.phoneModel.frameImageUrl = this.topMaterialUrl = item.frameImageUrl
				this.$refs.phoneModel.baseImageUrl = this.bottomMaterialUrl = item.baseImageUrl
        let extraData = item.materialMap
        eventTracking.event('SWITCH_MATERIAL', 'pages/myCustom',extraData)
        this.$refs.phoneModel.$forceUpdate()
			}
			this.$refs.phoneModel.materialListShow = false
      this.getDecorateListFun(); // 获取装饰品列表
			uni.$u.debounce(() => {
				this.onRefresh()
			})
		},
	switchTabs(e) {
      console.log(e);
      this.current = e
      // if(e.index === 0){
      // 	this.getCustomDetailFun()
      // }else if(e.index === 1){
      // 	this.getMyCustomListFun()
      // }

      // 新增状态恢复逻辑
      if (e === 0) { // 切换回DIY定制页时
        this.$nextTick(() => {
          // 检查是否存在持久化记录
          if (!uni.getStorageSync(this.persistKey)) {
            // 重置编辑状态
            this.activeDecorates = [];
            this.history = [];
            this.historyIndex = 0;
            this.decorateIndex = 0;
          }
          // 刷新必要数据
          this.getSkuListFun();
        });
      }


      this.onRefresh();
    },
    async toView(data) {
      console.log("toView", data);
      if (data.status === 1) {
        uni.$u.toast("生成中,请稍后查看");
      	return
      }
      if (data.status === 2) {
        uni.$u.toast("生成失败,请重新上传");
      	return
      }
      // 已读状态下不调用接口
      if (!data.read) {
        const res = await customProductRead({id:data.id});
        console.log("customProductRead", res);
        // this.getUnReadCount(); // 刷新未读消息
        this.checkUnReadMessage(); // 刷新未读消息
      }
      // if (data.status != 3) {
      // 	return
      // }
      
      if (data.type == 1) {
        uni.setStorageSync("customViewImageUrl", data.imageUrl);
        uni.navigateTo({
          url: `/pages/myCustom/customView?id=${data.id}`,
        });
      } else {
        this.imageData = data;
        this.$refs.customImageView.ontoggle();
      }
      // 找到当前点击项在前端数据中的索引
      const index = this.customList.findIndex(item => item.id === data.id);
      if (index !== -1) {
        this.$set(this.customList, index, { 
          ...this.customList[index],
          read: true // 标记为已读
        });
      }
      console.log("toView", this.customList);
    },

    // 下拉刷新
    onRefresh() {
      if (this.triggered) return;
      this.triggered = true;
      setTimeout(() => {
        this.getMyCustomListFun();
      }, 500);
    },
    // 复位
    onRestore() {
      this.triggered = false;
    },
    // 滑动到底部
    scrolltolower() {
      if (this.customList.length < this.pageSize) return
      this.getMyCustomListFun(this.customList[this.customList.length - 1].id)
    },
    // 删除定制图片
    deleteCustom(id, index, type) {
      const _this = this;
      uni.showModal({
        content: "确认要删除",
        success: function (res) {
          if (res.confirm) {
            deleteCustom({
              id,
            }).then((res) => {
              const index1 = _this.customList.findIndex((item) => {
                return item.id == id;
              });
              if (index1 != -1) {
                _this.customList.splice(index1, 1);
                // _this.getUnReadCount(); // 刷新未读消息
                _this.checkUnReadMessage();
              }
            });
          }
        },
      });
    },
    // async getUnReadCount(){
    //   const res = await unReadCount()
		// 	console.log("getUnReadCount", res)
    //   if(res.code === 200){
		// 			//unReadCount大于0就显示红色数字，如果==0则判断hasUnRead是否为true,为true则显示红点
		// 			if(res.data.unReadCount > 0){
		// 				uni.setTabBarBadge({
		// 					index: 2,
		// 					text: res.data.unReadCount.toString()
		// 				})
		// 			}else{
		// 				if(res.data.hasUnRead){
		// 					uni.showTabBarRedDot({
		// 						index: 2
		// 					})
		// 				}else{
		// 					uni.hideTabBarRedDot({
		// 						index: 2
		// 					})
		// 				}
		// 			}
		// 		}
    // },
    handlePageReturn(data) {
      console.log('handlePageReturn',data); // 接收子组件传递的数据
      if(data.from === 'customView'){
        // this.getMyCustomListFun(); // 切换到"我的定制"时刷新数据
        this.pageReturn = true;
      }
    },
    shouldSelectCustomized() {
      // 从缓存或store中获取红点状态
      return uni.getStorageSync('hasCustomizedBadge') 
    },
    // 在获取用户数据后更新current
    fetchUserData() {
      // ...原有逻辑...
      this.current = this.shouldSelectCustomized() ? 1 : 0
    },
  },
  // 在页面脚本中添加生命周期函数
  onTabItemTap(e) {
    console.log('当前激活Tab索引:', e.index)
    console.log('页面路径:', e.pagePath)
    eventTracking.event('DIY_CUSTOMIZATION', e.pagePath, );
    // 执行自定义业务逻辑
    if(e.index === 1) {
      this.getMyCustomListFun() // 切换到"我的定制"时刷新数据
    }
  },
  onHide() {
    this.lastMyCustomMaterialMap = this.getMyCustomMaterial.materialMap?.materialMap ?? {}; //切换底部tab栏时，保存上一次的材质
    this.pageReturn = false;
  },
  onUnload() {
    if (this.$refs.diyEdit) {
      // 主动销毁Canvas引用
      this.$refs.diyEdit.$el = null;
    }
    uni.$off('pageReturn')//移除监听上一页面返回事件
    this.pageReturn = false;
  },
  async onShow() {
    uni.$on('pageReturn',this.handlePageReturn)//监听上一页面返回事件

    // this.checkUnReadMessage().then(hasUnread => {
    //     console.log("hasUnread", hasUnread,this.pageReturn );
    //     this.current = hasUnread || this.pageReturn ? 1 : 0; // 1:我的定制 0:DIY定制  上一页返回时，必须切换到我的定制页，
    //     console.log("onShowcurrent", this.current);
    //     this.$forceUpdate();
    // });

    // 增加await确保异步操作完成
    const hasUnread = await this.checkUnReadMessage();
    
    // 使用$nextTick确保DOM更新
    this.$nextTick(() => {
      // 关键修改：仅当非上传状态时才执行current切换
      if (!this.isUploading) {
        this.current = (hasUnread || this.pageReturn) ? 1 : 0; // 1:我的定制 0:DIY定制  上一页返回时，必须切换到我的定制页，
      }
    });


    // this.getUnReadCount(); // 刷新未读消息
    uni.showLoading({ title: '加载中...', mask: true });
    // uni.hideTabBarRedDot({
    //   index: 1,
    // });
    const currentMaterialMap = this.getMyCustomMaterial.materialMap; // 当前机型和材质
	  this.$nextTick(() => {
      // this.getCustomDetailFun();
      this.getSkuListFun(); // 获取定制列表
    });
    if(this.current === 1 && uni.getStorageSync('hasUnsavedChanges')) {
      uni.removeStorageSync('hasUnsavedChanges'); // 清除未保存的标记
      this.onRefresh(); // 切换到"我的定制"时刷新数据
    }
    // 机型变化检测
    if (
      Object.keys(this.lastMyCustomMaterialMap).length !== 0 &&
      (this.lastMyCustomMaterialMap[10] !== currentMaterialMap[10] ||
        this.lastMyCustomMaterialMap[11] !== currentMaterialMap[11])
    ) {
      console.log("检测到机型变化，自动刷新");
      uni.$u.debounce(() => {
        // 触发下拉刷新
        this.onRefresh();
      });
    } else {
      console.log("机型未变化，无需刷新");
    }

    // 记录当前机型
    this.lastMyCustomMaterialMap = currentMaterialMap;

    // this.getCustomDetailFun()
    // this.getMyCustomListFun()
  },
  onLoad() {
    this.restoreEditSession(); // 新增状态恢复
    // console.log('onLoad',e);
    // if (e.id) {
    // 	this.getCustomDetail(e.id)
    // 	uni.showLoading()
    // 	this.isEdit = true
    // }
    // 初始记录当前机型和材质
    this.lastMyCustomMaterialMap = this.getMyCustomMaterial.materialMap?.materialMap ?? {}; 
    uni.$u.debounce(() => {
      // this.getCustomDetailFun()
      // this.getMyCustomListFun()
    });
  },
  created() {
      
  },
  mounted() {
    this.$nextTick(() => {
      // this.getCustomDetailFun();
      this.getSkuListFun(); // 获取定制列表
    });
  },
  onUnload() {},
  onShareAppMessage() {
    return {
      title: "我发现了一款可以DIY定制手机壳的小程序，快来看看吧",
      path: `/pages/index/index`,
    };
  },
};
</script>

<style lang="scss">
.mycustom-page {
  touch-action: none;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  .mymenu {
		margin-bottom: 10rpx !important;
	}
  .tabs {
    padding: 17rpx;
    background-color: #fff;
  }

  .decorate-content {
    height: calc(100vh - 450rpx); /* 动态计算高度 */
    overflow: hidden;
    position: relative;

    .tips {
      position: absolute;
      top: 600rpx;
      left: 50%;
      transform: translateX(-50%);
      color: #efefef;
      z-index: 1;
      font-size: 35rpx;
      text-shadow: 0rpx 0rpx 11rpx #333;
    }

    .eidt-view {
      touch-action: none; // 禁用触摸滚动（防止页面在编辑区滚动）
      overflow: hidden;    // 隐藏溢出内容（防止页面在编辑区滚动）
      height: 810rpx;
      background-color: #fff;
      display: flex;
      justify-content: center;
    }

    .type-tabbar {
      height: 140rpx;
      width: 100%;
      display: flex;
      position: fixed;
      bottom: 100rpx;
      background: #fff;
      overflow: hidden;
      z-index: 99;

      .type-item {
        flex: 1;
        text-align: center;
        margin: 20rpx 20rpx 0;

        &.active {
          background-color: #e8e8e8;
        }

        image {
          height: 80rpx;
          width: 60rpx;
        }

        text {
          font-size: 23rpx;
        }
      }
    }

    .operation-tabbar {
        position: fixed; // 改为固定定位
				bottom: 250rpx;
				left: 0;
				right: 0;
				// z-index: 9999;     // 确保最高层级
				height: 100rpx;
				background: #fff;
				box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.1);
				// position: relative;

      .left-control {
        height: 70rpx;
        display: flex;
        align-items: center;
        margin-left: 23rpx;

        .translate {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
        }

        .control-btn {
          width: 70rpx;
          height: 60rpx;

          &.next {
            transform: scaleX(-1);
          }

          &.left {
            transform: rotate(0deg);
          }

          &.up {
            transform: rotate(90deg);
          }

          &.down {
            transform: rotate(270deg);
          }

          &.right {
            transform: rotate(180deg);
          }

          &.disable {
            opacity: 0.5;
          }
        }
      }

      .coverage {
        position: absolute;
        top: 0rpx;
        right: 17rpx;
        height: 70rpx;
        width: 70rpx;
        background: #fff;
        box-shadow: 0rpx 1rpx 11rpx 0rpx #666;
        border-radius: 50%;
        padding: 15rpx;

        image {
          height: 100%;
          width: 100%;
        }
      }
    }

    .decorate-list {
		
    //   height: calc(100% - 880rpx);
	  height: calc(100% - 650rpx);
      width: 100%;
      position: absolute;
      border-top: 1rpx solid #e2e2e2;
      transition: 0.3s;
      bottom: 140rpx;
      background-color: #f6f6f6;
      z-index: 98;
      display: flex;
      flex-direction: column;

      &.more {
        height: calc(100% - 200rpx);
      }

      &.hide {
        bottom: -320rpx;
        height: calc(100% - 950rpx);
      }

      .tips1 {
        position: absolute;
        top: 18rpx;
        left: 30rpx;
        color: #969696;
      }

      .more {
        height: 60rpx;
        width: 118rpx;
        background-color: #f6f6f6;
        position: absolute;
        top: -60rpx;
        left: 17rpx;
        border-radius: 17rpx 17rpx 0rpx 0;
        border: 1rpx solid #e2e2e2;
        border-bottom: none;
        text-align: center;
        line-height: 60rpx;
        color: #999;
      }

      .decorate-scroll {
        height: calc(100% - 77rpx);
        // overflow: hidden;
        width: 100%;
        padding: 17rpx 0;
        flex-grow: 1;

        .list {
          &.ai-list {
            grid-template-columns: repeat(3, 1fr);
            .decorate-item {
              // height: 115rpx;
              height: 90rpx;
			  // GPU加速渲染
			  transform: translateZ(0);
			  will-change: transform;
			  backface-visibility: hidden;
              .image {
                height: 50rpx;
              }
            }
          }
          grid-template-columns: repeat(4, 1fr);
          grid-gap: 17rpx;
          display: grid;
          margin: 0 34rpx 17rpx;

          .decorate-item {
            background-color: #fff;
            height: 165rpx;
            position: relative;
			// GPU加速渲染
			transform: translateZ(0);
			will-change: transform;
			backface-visibility: hidden;

            &.upload {
              padding: 34rpx;
              text-align: center;

              image {
                height: 50rpx;
                width: 50rpx;
                margin: 17rpx;
                box-sizing: border-box;
              }

              .text {
                white-space: nowrap;
              }
            }

            // image {
            // 	height: calc(100% - 35rpx);
            // 	width: calc(100% - 35rpx);
            // 	margin: 17rpx;
            // }

            // image {
            // 	height: calc(100% - 10rpx);
            // 	width: calc(100% - 10rpx);
            // 	margin: 5rpx;
            // }

            image {
              height: calc(120% - 25rpx);
              width: calc(100%);
              margin: 5rpx;
            }

            &.temp-item {
              height: 214rpx;
              overflow: hidden;

              image {
                height: 100%;
                width: 100%;
                margin: auto;
                transform: scale(1.3);
              }
            }

            &.active {
              opacity: 0.7;

              .radio {
                position: absolute;
                right: 17rpx;
                top: 17rpx;
              }
            }

            .delete {
              height: 43rpx;
              width: 43rpx;
              background: #333333;
              color: #fff;
              font-size: 43rpx;
              position: absolute;
              top: 17rpx;
              right: 17rpx;
              text-align: center;
              line-height: 43rpx;
              border-radius: 50%;
              opacity: 0.8;
            }
            .redDot{
              /* height: 43rpx;
              width: 43rpx;
              background-color: red;
              font-size: 43rpx;
              position: absolute;
              top: 17rpx;
              left: 0rpx;
              text-align: center;
              line-height: 43rpx;
              border-radius: 50%;
              opacity: 0.8; */
            }
          }
        }

        .get-ai-image {
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          .get-ai-image-text {
            width: 200rpx;
            height: 50rpx;
            line-height: 50rpx;
            text-align: center;
            border: 1px solid #999;
            border-radius: 50rpx;
          }
        }
      }
    }
  }

  .btn {
    // margin: 26rpx 35rpx;
    width: 100%;
    position: fixed;
    bottom: 0;

    .btn-next {
      margin: 20rpx auto;
      width: 90%;
      height: 78.8rpx;
      border-radius: 78rpx;
      font-size: 35rpx;
      box-sizing: border-box;
      text-align: center;
      line-height: 78.8rpx;
      background-color: #333;
      color: #fff;

      &.disable {
        opacity: 0.7;
      }
    }
  }

  .scroll-box {
    // flex: 1;
    // overflow: hidden;
    height: 100%;
    ::-webkit-scrollbar {
      width: 0;
      height: 0;
      color: transparent;
    }

    .custom {
      // display: block;  // 修改flex布局为block
      // padding: 20rpx 14rpx; // 增加内边距
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin: 30rpx 14rpx;

      .custom-item {
        width: 350rpx;
        height: 670rpx;
        border-radius: 21rpx;
        overflow: hidden;
        background-color: #fff;
        margin-bottom: 33rpx;
        position: relative;

        .img {
          height: 620rpx;
          width: 350rpx;
        }

        .img2 {
          height: 455rpx;
          width: 455rpx;
          position: relative;
          left: -52.5rpx;
          top: 100rpx;
        }

        .resolut2 {
          position: absolute;
          bottom: 6rpx;
          left: 50%;
          transform: translateX(-50%);
          line-height: 40rpx;
        }

        .resolut {
          font-size: 28rpx;
          text-align: center;
          line-height: 40rpx;
        }

        .wait {
          height: 620rpx;
          width: 350rpx;
          position: absolute;
          top: 0;
          left: 0;
          background-color: #000000b5;
          line-height: 620rpx;
          text-align: center;

          image {
            height: 52.5rpx;
            width: 52.5rpx;
          }
        }

        .err {
          height: 620rpx;
          width: 350rpx;
          position: absolute;
          top: 0;
          left: 0;
          background-color: #000000b5;
          line-height: 620rpx;
          text-align: center;

          text {
            color: #ff0000;
            font-weight: 700;
          }
        }

        .delete {
          height: 43rpx;
          width: 43rpx;
          background: #333333;
          color: #fff;
          font-size: 43rpx;
          position: absolute;
          top: 17rpx;
          right: 17rpx;
          text-align: center;
          line-height: 43rpx;
          border-radius: 50%;
          opacity: 0.8;
        }
      }
    }
  }
}
// 单独修改子组件的样式，不使用全局样式 
.mycustom-page .mymenu{
  margin-bottom: 0rpx;
  height: 57rpx !important;
}
.subsection {
  height: 57rpx !important;
}
.sub-block{
  width: 170rpx !important;
  height: 43rpx !important;
  line-height: 43rpx !important;
  // top: 7rpx !important;
  
}

.sub-item {
  width: 190rpx!important;
  height: 55rpx !important;
  line-height: 55rpx !important;
  margin: 0rpx !important;
  font-size: 28rpx !important;
}
</style>
